import { RouteLocationNormalized, RouteRecordRaw } from "vue-router"
import { useUserStore } from "@/store"

export default function usePermission() {
  const userStore = useUserStore()

  const accessRouter = (route: RouteLocationNormalized | RouteRecordRaw) => {
    return (
      !route.meta?.requiresAuth ||
      !route.meta?.roles ||
      route.meta?.roles?.includes("*") ||
      route.meta?.roles?.find(role => userStore.roles?.includes(role as any))
    )
  }

  const findFirstPermissionRoute = (_routers: any, role = ["admin"]) => {
    const cloneRouters = [..._routers]
    while (cloneRouters.length) {
      const firstElement = cloneRouters.shift()
      if (
        firstElement?.meta?.roles?.find((el: string) => {
          return el.includes("*") || role.includes(el)
        })
      )
        return { name: firstElement.name }
      if (firstElement?.children) {
        cloneRouters.push(...firstElement.children)
      }
    }
    return null
  }

  const whiteListRouter = (whiteList: any[], targetName: string): boolean => {
    for (const menuItem of whiteList) {
      if (menuItem.name === targetName) {
        return true
      }
      if (menuItem.children && menuItem.children.length > 0) {
        if (whiteListRouter(menuItem.children, targetName)) {
          return true
        }
      }
    }

    return false
  }

  return {
    accessRouter,
    findFirstPermissionRoute,
    whiteListRouter
  }
}
